'use strict';

import { Navigation } from '../views/global/navigation/index';
import * as config from '../constants/apiConfig';
import session from './AsyncSession';
import qs from 'qs';

import {
    AsyncStorage,
    Platform
} from 'react-native';

import axios from 'axios';

async function request(path, data, extra, customLoadComp){
    data = data || {};
    var {stoken, user} = session.data();
    var headers = extra && extra.headers;
    var method= (extra && extra.method) || 'GET';
    var ticket = data && data.ticket ? data.ticket:stoken;
    var json = extra && extra.json;
    console.log('api=======request=======stoken',stoken);
    console.log('api=======request=======user',user);
    if(stoken){
        data.stoken=stoken;
    }
    if (json) {
        headers['Content-Type'] = 'application/json';
    }else{
        headers['Content-Type'] = 'application/x-www-form-urlencoded';
    }
    headers['source'] = 'app';
    //用户id
    if(user){
        headers['user_id'] = user.id;
    }

    if (ticket) {
        headers['t'] = ticket;
    }

    if (path && path.indexOf("regSendCode") != -1) {
        headers['product'] = 'HeChang';
    }
    console.log('api-----path',path);
    console.log('api-----headers',headers);
    console.log('api-----data',qs.stringify(data));
    console.log('api-----data',data);
    try{
        let response = await axios({
            baseURL: config.API_URL,
            url: path,
            method,
            data: json?data:qs.stringify(data),
            headers
        });
        console.log('api request path is:'+path,response.data);
        let d = response.data;
        if (d.cd == "-1") {
            goToLogin();
        }
        return d;

    }catch(e){
        console.log('网络请求失败!!!!' + e);
        return {cd:1, msg: "网络开了一会儿小差，请稍后重试", data:null};
    }
}

async function upload(path,file,data){
    try{
        var {stoken} = session.data();
        var ticket = data && data.ticket ? data.ticket:stoken;
        let headers = {"apiver":"1.0.0",'device':Platform.OS};
        headers['source'] = 'app';
        headers['Content-Type'] = 'multipart/form-data';
        if (ticket) {
            headers['t'] = ticket;
        }
        let data1 = new FormData();
        data1.append('file',file)
        data1.append('type',data);
        console.log('upload=========data',data);
        let response = await axios({
            baseURL: config.API_URL,
            url: path,
            method:'POST',
            data: data1,
            headers
        });
        console.log('upload=========response',response);
        return response.data
    }catch(e){
        console.log('网络请求失败!!!!' + e);
        return {cd:1, msg: "网络开了一会儿小差，请稍后重试", data:null};
    }
}


// async function requestJson(path, data, extra, customLoadComp){
//     data = data || {};
//     var {stoken, user} = session.data();
//     var headers = extra && extra.headers;
//     var method= (extra && extra.method) || 'GET';
//     var ticket = data && data.ticket ? data.ticket:stoken;
//     console.log('api=======request=======stoken',stoken);
//     console.log('api=======request=======user',user);
//     if(stoken){
//         data.stoken=stoken;
//     }
//     headers['Content-Type'] = 'application/json';
//     headers['source'] = 'app';
//     //用户id
//     if(user){
//         headers['user_id'] = user.id;
//     }

//     if (ticket) {
//         headers['t'] = ticket;
//     }

//     if (path && path.indexOf("regSendCode") != -1) {
//         headers['product'] = 'HeChang';
//     }
//     console.log('api-----path',path);
//     console.log('api-----headers',headers);
//     console.log('api-----data',data);
//     try{
//         let response = await axios({
//             baseURL: config.API_URL,
//             url: path,
//             method,
//             data: data,
//             headers
//         });
//         console.log('api request path is:'+path,response.data);
//         let d = response.data;
//         if (d.cd == "-1") {
//             goToLogin();
//         }
//         return d;

//     }catch(e){
//         console.log('网络请求失败!!!!' + e);
//         return {cd:1, msg: "网络开了一会儿小差，请稍后重试", data:null};
//     }
// }

function post(path, data, customLoadComp, headers){
    if (path == '/order/createorder') {
        return request(path, data, {method:'POST',headers:(headers || {"apiver":"1.0.0",'device':Platform.OS}),json:true}, customLoadComp);
    }
    return request(path, data, {method:'POST',headers:(headers || {"apiver":"1.0.0",'device':Platform.OS})}, customLoadComp);
}

// function postJson(path, data, customLoadComp, headers){
//     return requestJson(path, data, {method:'POST',headers:(headers || {"apiver":"1.0.0",'device':Platform.OS})}, customLoadComp);
// }





async function get(path, data, headers={}){
    try{
        var {stoken} = session.data();
        var ticket = data && data.ticket ? data.ticket:stoken;
        headers['source'] = 'app';
        if (ticket) {
            headers['t'] = ticket;
        }
        console.log('test=========get',headers);
        let response = await axios.get(path,{
                baseURL:config.API_URL,
                url:path,
                method:'get',
                params:data,
                headers:{...headers,"apiver":"1.0.0",'device':Platform.OS}
            })
        return response.data;
    }catch(e){
        console.log('网络请求失败!!!!' + e);
        return {cd:1, msg: "网络开了一会儿小差，请稍后重试", data:null};
    }

}

function goToLogin() {
    Navigation.startSingleScreenApp({
      screen: {
          screen: 'housekeeperapp.loginindex',
          animated: true,
          navigatorStyle: {
              navBarHidden:true,
              statusBarBlur: true,
              statusBarTextColorScheme: 'light'
          }
      },
      passProps: {
      },
      animationType: 'fade'
    });
}

module.exports={post:post,get,upload};
